import { prisma } from '@/lib/prisma';
import { PopularTripCard } from '@/app/components/PopularTripCard';
import { TripSearch } from '@/app/components/TripSearch';
import { getServerSession } from 'next-auth';
import { authOptions } from '@/app/api/auth/auth.config';
import { unstable_noStore as noStore } from 'next/cache';
import { TripWithDetails } from '@/app/types';

async function getPopularTrips(searchTerm?: string, userId?: string) {
  // 禁用缓存
  noStore();
  
  const trips = await prisma.trip.findMany({
    where: {
      OR: [
        { isOfficial: true },  // 官方行程
        { isPublic: true }     // 公开的用户行程
      ],
      ...(searchTerm ? {
        OR: [
          { title: { contains: searchTerm } },
          { description: { contains: searchTerm } }
        ]
      } : {})
    },
    include: {
      activities: true,
      user: {
        select: {
          id: true,
          name: true,
          username: true
        }
      },
      savedBy: {
        include: {
          user: {
            select: {
              id: true,
              username: true,
              name: true,
              email: true,
              password: true,
              createdAt: true,
              updatedAt: true
            }
          }
        }
      },
      _count: {
        select: {
          activities: true,
          savedBy: true,
          comments: true
        }
      }
    },
    orderBy: [
      { savedBy: { _count: 'desc' } },  // 按收藏数排序
      { createdAt: 'desc' }             // 其次按创建时间排序
    ]
  });

  // 转换数据格式以匹配 TripWithDetails 类型
  return trips.map(trip => ({
    ...trip,
    savedBy: trip.savedBy.map(save => save.user),
    isSaved: trip.savedBy.some(save => save.user.id === userId)
  })) as TripWithDetails[];
}

export default async function PopularTripsPage({
  searchParams
}: {
  searchParams: { q?: string }
}) {
  const session = await getServerSession(authOptions);
  const trips = await getPopularTrips(searchParams.q, session?.user?.id);

  return (
    <div className="max-w-7xl mx-auto py-8 px-4 sm:px-6 lg:px-8">
      <h1 className="text-3xl font-bold text-blue-900 mb-8">热门行程</h1>
      <TripSearch />
      {trips.length === 0 ? (
        <div className="text-center py-12 bg-gray-50 rounded-lg">
          <p className="text-gray-500">
            {searchParams.q ? '没有找到相关行程' : '暂无热门行程'}
          </p>
        </div>
      ) : (
        <div className="grid gap-6 md:grid-cols-2 lg:grid-cols-3">
          {trips.map((trip) => (
            <PopularTripCard 
              key={trip.id} 
              trip={trip} 
              initialSaved={trip.isSaved}
            />
          ))}
        </div>
      )}
    </div>
  );
} 